import InterceptorManager from './InterceptorManager'

import type { DefaultRequestConfig, AxiosRequestConfig } from '../index'

type MergeConfig = DefaultRequestConfig & AxiosRequestConfig

class Axios {
  defaults:DefaultRequestConfig
  interceptors: { request:InterceptorManager, response:InterceptorManager }
  request: (config:MergeConfig) => Promise<AxiosRequestConfig>
  constructor (instanceConfig:DefaultRequestConfig) {
      this.defaults = instanceConfig
      this.interceptors = {
          request: new InterceptorManager(),
          response: new InterceptorManager()
      }     
  }
}

Axios.prototype.request = function request (config) {
    if (typeof (config as AxiosRequestConfig) === 'string') {
        config = arguments[1] || {};
        config.url = arguments[0];
    } else {
        config = config || {}
    }

    // TODO 简化版合并 暂时替代
    config = {...(this as Axios).defaults, ...config}

    var chain:any = ['dispatchRequest'/** ajax请求 */, undefined];  // undefined 凑数  为了保证每次去掉两项不剩下
    var promise = Promise.resolve(config);

    (this as Axios).interceptors.request.forEach(function unshiftRequestInterceptors (interceptor) {
        chain.unshift(interceptor.fulfilled, interceptor.reject)
    });

    (this as Axios).interceptors.response.forEach(function pushRequestInterceptors (interceptor) {
        chain.push(interceptor.fulfilled, interceptor.reject)
    });

    // 循环执行 每次执行去掉两项
    while (chain.length) {
        promise = promise.then(chain.shift(), chain.shift()); // promise 的原因 chain 内的函数会自动执行
        // fulfilled 就是then 的第一个参数  成功后执行
        // reject 是then 的第二个参数 失败的时候会调用
    }

    return promise
}

export default Axios